package com.example.final_project.service.impl;

import com.example.final_project.entity.Book;
import com.example.final_project.entity.Inventory;
import com.example.final_project.mapper.BookMapper;
import com.example.final_project.service.BookService;
import com.example.final_project.service.InventoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private InventoryService inventoryService;

    @Override
    @Transactional
    public boolean add(Book book) {
        boolean bookAdded = bookMapper.insert(book) > 0;
        if (bookAdded) {
            // 如果教材添加成功，则为该教材创建一条库存记录，初始库存为0
            Inventory inventory = new Inventory();
            inventory.setBookId(book.getId()); // 使用新添加教材的ID
            inventory.setQuantity(0); // 初始库存设置为0
            return inventoryService.add(inventory); // 添加库存记录
        }
        return false;
    }

    @Override
    @Transactional
    public boolean update(Book book) {
        return bookMapper.update(book) > 0;
    }

    @Override
    @Transactional
    public boolean delete(Long id) {
        // 先删除关联的库存记录
        inventoryService.deleteByBookId(id);
        // 再删除教材记录
        return bookMapper.deleteById(id) > 0;
    }

    @Override
    public Book getById(Long id) {
        return bookMapper.selectById(id);
    }

    @Override
    public PageInfo<Book> getList(String name, String isbn, String author, Long publisherId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Book> list = bookMapper.selectList(name, isbn, author, publisherId);
        return new PageInfo<>(list);
    }

    @Override
    public List<Book> getAll() {
        List<Book> books = bookMapper.selectList(null, null, null, null);
        if (books != null) {
            for (Book book : books) {
                Integer stock = inventoryService.getStockByBookId(book.getId());
                book.setStock(stock != null ? stock : 0);
            }
        }
        return books;
    }

    @Override
    public int countAllBooks() {
        return bookMapper.countAllBooks();
    }

    @Override
    public List<Book> getLatestBooks(int limit) {
        return bookMapper.getLatestBooks(limit);
    }
} 